package org.chs.ts.batch.factory;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.chs.ts.base.batch.exec.entity.BatchDailyBasicTaskStepExec;
import org.chs.ts.base.batch.set.entity.BatchDailyBasicTaskPublish;
import org.chs.ts.base.batch.set.entity.BatchDailyBasicTaskStepSet;
import org.chs.ts.base.batch.vo.entity.BatchDailyCancelReq;
import org.chs.ts.base.batch.vo.entity.BatchDailyConfirmReq;
import org.chs.ts.base.constant.CommonConstant;
import org.chs.ts.base.vo.Result;
import org.chs.ts.batch.service.IBatchDailyBasicTaskPublishService;
import org.chs.ts.batch.service.IBatchDailyBasicTaskStepExecService;
import org.chs.ts.batch.service.IBatchDailyBasicTaskStepSetService;

import org.chs.ts.batch.util.CommonUtil;
import org.chs.ts.batch.util.ConvertToUtil;
import org.chs.ts.batch.util.ParameterUtil;
import org.chs.ts.base.common.util.DateUtils;

import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;

/**
 * @Compay 盛唐天行
 * @Author: wuwei
 * @Censor By wuwei
 * @Sence 2024/6/14 10:40
 * @Modify 2024/6/14 10:40
 * @Description
 */
@Slf4j
@Service
public class TaskDailyExecFactory {

    @Resource
    private IBatchDailyBasicTaskStepExecService dailyBasicTaskStepExecService;

    @Resource
    private IBatchDailyBasicTaskStepSetService dailyBasicTaskStepSetService;

    @Resource
    private IBatchDailyBasicTaskPublishService dailyBasicTaskPublishService;

    @Resource
    private ParameterUtil parameterUtil;


    /**
     * 验证 提交 日间跑批任务对象 有效性
     *
     * @param taskPublish 日间跑批任务发布对象
     * @return 验证结果
     */
    public Result<String> checkConfirmDailyTask(BatchDailyConfirmReq taskPublish) {

        if (Strings.isBlank(taskPublish.getTaskPubId())) {
            if (Strings.isBlank(taskPublish.getIsReplay())) {
                log.info("checkConfirmDailyTask -> isReplay is empty!");
                return Result.error("isReplay 不能为空");
            }

            if (Strings.isBlank(taskPublish.getBatchSysCode())) {
                log.info("checkConfirmDailyTask -> BatchSysCode is empty!");
                return Result.error("batchSysCode 不能为空");
            }

            String mwbpTransDay = parameterUtil.getParameterByCode(CommonConstant.MWBP_TRANS_DAY);

            if (Strings.isBlank(taskPublish.getStartDate())) {
                log.info("checkConfirmDailyTask -> StartDate is empty!");
                return Result.error("startDate 不能为空");
            }

            if (Long.compare(Long.parseLong(taskPublish.getStartDate()), Long.parseLong(mwbpTransDay)) < 0) {
                log.info("checkConfirmDailyTask -> StartDate < mwbpTransDay ");
                return Result.error("startDate 不能为小于业务时间");
            }

            if (Strings.isBlank(taskPublish.getEndDate())) {
                log.info("checkConfirmDailyTask -> EndDate is empty!");
                return Result.error("endDate 不能为空");
            }

            if (Long.compare(Long.parseLong(taskPublish.getEndDate()), Long.parseLong(mwbpTransDay)) < 0) {
                log.info("checkConfirmDailyTask -> EtartDate < mwbpTransDay ");
                return Result.error("endDate 不能为小于业务时间");
            }


            if (Strings.isBlank(taskPublish.getStepParamsVersion())) {
                log.info("checkConfirmDailyTask -> StepParamsVersion is empty!");
                return Result.error("stepParamsVersion 不能为空");
            }

            if (Strings.isBlank(taskPublish.getExecCycle())) {
                log.info("checkConfirmDailyTask -> ExecCycle is empty!");
                return Result.error("execCycle 不能为空");
            }

            if (!validExecCycle(taskPublish.getExecCycle())) {
                log.info("checkConfirmDailyTask -> ExecCycle is unvalid!");
                return Result.error("execCycle 不合法！");
            }

            if (Strings.isBlank(taskPublish.getStepNo())) {
                log.info("checkConfirmDailyTask -> stepNo is empty!");
                return Result.error("stepNo 不能为空");
            } else {
                if (dailyBasicTaskStepSetService.list(new LambdaQueryWrapper<BatchDailyBasicTaskStepSet>()
                        .eq(BatchDailyBasicTaskStepSet::getStepNo, taskPublish.getStepNo())
                        .eq(BatchDailyBasicTaskStepSet::getBatchSysCode, taskPublish.getBatchSysCode())).isEmpty()) {
                    return Result.error("日间跑批模板不存在[stepNo]为" + taskPublish.getStepNo() + "[batchSysCode]为" + taskPublish.getBatchSysCode());
                }
            }
        } else {
            BatchDailyBasicTaskPublish dailyTaskPubObj =
                    dailyBasicTaskPublishService.getOne(new LambdaQueryWrapper<BatchDailyBasicTaskPublish>()
                            .eq(BatchDailyBasicTaskPublish::getTaskPubId, taskPublish.getTaskPubId())
                            .eq(BatchDailyBasicTaskPublish::getBatchSysCode, taskPublish.getBatchSysCode())
                    );

            if (dailyTaskPubObj == null || !dailyTaskPubObj.getTaskPubStauts().equals("1")) {
                return Result.error("跑批日间任务请求表不存在[taskPubId]为" + taskPublish.getTaskPubId() + "或跑批日间任务发布状态[taskPubStauts]不为1");

            }
            if (dailyBasicTaskStepSetService.list(new LambdaQueryWrapper<BatchDailyBasicTaskStepSet>()
                    .eq(BatchDailyBasicTaskStepSet::getStepNo, dailyTaskPubObj.getStepNo())
                    .eq(BatchDailyBasicTaskStepSet::getBatchSysCode, dailyTaskPubObj.getBatchSysCode())).isEmpty()) {
                return Result.error("日间跑批模板不存在[stepNo]为" + taskPublish.getStepNo() + "[batchSysCode]为" + taskPublish.getBatchSysCode());
            }
        }

        return Result.ok();
    }

    /**
     * 验证 执行周期 有效性 (执行周期daily@HHmmss-每天、everyHour@HHmmss-每小时、specifyDay@12,12@HHmmss-指定日期、specifyTime@12,23@HHmmss-指定时间)
     *
     * @param execCycle 执行周期
     * @return 验证结果
     */
    private boolean validExecCycle(String execCycle) {
        if (Strings.isBlank(execCycle) || !execCycle.contains("@")) {
            return false;
        }
        if (execCycle.length() > 200) {
            return false;
        }


        String[] execCycleList = execCycle.split("@");
        if (execCycleList.length < 2 && (execCycleList[0].equals("daily") || execCycleList[0].equals("everyHour"))) {
            return false;
        }

        if (execCycleList.length < 3 && (execCycleList[0].equals("specifyDay") || execCycleList[0].equals("specifyTime"))) {
            return false;
        }

        if ((execCycleList[0].equals("daily") || execCycleList[0].equals("everyHour"))) {

            return validTime(execCycleList[1]);
        }

        if ((execCycleList[0].equals("specifyDay") || execCycleList[0].equals("specifyTime"))) {

            return validTime(execCycleList[2]);
        }


        return validExecCycleParam(execCycleList[0], execCycleList[1].split(","));

    }

    private boolean validTime(String execCycleTime) {
        String validTimeRegex = "^[0-2][0-9][0-5][0-9][0-5][0-9]";
        return Pattern.compile(validTimeRegex).matcher(execCycleTime).matches();
    }

    private boolean validExecCycleParam(String execCycleType, String[] execCycleParam) {
        // 定日期 要求 参数 为整形并小于等于31
        String specifyDayRegex = "^((0?[1-9])|((1|2)[0-9])|30|31)";
        // 指定时间 要求 参数 为整形并小于等于24
        String specifyTimeRegex = "^((0?[1-9])|(1[0-9])|(2[0-4]))";
        String regex = execCycleType.equals("specifyDay") ? specifyDayRegex : (execCycleType.equals("specifyTime") ? specifyTimeRegex : "");
        for (String param : execCycleParam) {
            if (!Pattern.compile(regex).matcher(param).matches()) {
                return false;
            }
        }
        return true;
    }

    /**
     * 创建日间跑批计划
     *
     * @param taskPublish 日间跑批计划请求对象
     * @return 创建结果
     */
    public Result<String> confirmDailyTask(BatchDailyConfirmReq taskPublish) {
        BatchDailyBasicTaskPublish obj;
        boolean taskPublishOptResult = false;
        if (Strings.isBlank(taskPublish.getTaskPubId())) {
            // 获取跑批模板
            BatchDailyBasicTaskStepSet taskStepSet =
                    dailyBasicTaskStepSetService.getOne(new LambdaQueryWrapper<BatchDailyBasicTaskStepSet>()
                            .eq(BatchDailyBasicTaskStepSet::getStepNo, taskPublish.getStepNo())
                            .eq(BatchDailyBasicTaskStepSet::getBatchSysCode, taskPublish.getBatchSysCode()));
            // 验证有效性
            Result<String> validBatchDailyTaskPublishResult = validBatchDailyTaskPublish(taskPublish, taskStepSet);
            if (!validBatchDailyTaskPublishResult.isSuccess()) {
                return validBatchDailyTaskPublishResult;
            }
            String taskPubId = SernoFactory.createSerno("taskPubId");

            obj = ConvertToUtil.convertToV(new BatchDailyBasicTaskPublish(), taskPublish, new HashMap<String, Object>() {
                {
                    put("taskPubId", taskPubId);
                    put("taskPubStauts", "1");
                    put("stepParamsDescription", taskStepSet.getStepParamsDescription());
                    put("sliceReqClass", taskStepSet.getSliceReqClass());
                    put("sliceServiceClass", taskStepSet.getSliceServiceClass());
                    put("stepName", taskStepSet.getStepName());

                }
            });

            taskPublishOptResult = dailyBasicTaskPublishService.save(obj);
        } else {
            obj = dailyBasicTaskPublishService.getOne(new LambdaQueryWrapper<BatchDailyBasicTaskPublish>()
                    .eq(BatchDailyBasicTaskPublish::getTaskPubId, taskPublish.getTaskPubId())
                    .eq(BatchDailyBasicTaskPublish::getBatchSysCode, taskPublish.getBatchSysCode())
            );
            if (obj == null || !obj.getTaskPubStauts().equals("1")) {
                return Result.error("跑批日间任务请求表不存在[taskPubId]为" + taskPublish.getTaskPubId() + "或跑批日间任务发布状态[taskPubStauts]不为1");
            }

            taskPublishOptResult = dailyBasicTaskPublishService.updateById(obj);
        }

        if (taskPublishOptResult && createDailyTaskStepExecByDailyTaskPublish(obj)) {
            // taskPublish 增加成功 增加
            return Result.ok();
        } else {
            if (Strings.isBlank(taskPublish.getTaskPubId())) {
                dailyBasicTaskPublishService.removeById(obj);
            }
            return Result.error((taskPublishOptResult ? ("跑批日间任务请求操作" + (Strings.isBlank(taskPublish.getTaskPubId()) ? "新增" : "更新")) :
                    "跑批日间任务执行表新增") + "失败");

        }


    }

    private boolean createDailyTaskStepExecByDailyTaskPublish(BatchDailyBasicTaskPublish obj) {
        // daily@HHmmss-每天、everyHour@HHmmss-每小时、specifyDay@12,12@HHmmss-指定日期、specifyTime@12,23@HHmmss-指定时间
        String[] execCycleParams = obj.getExecCycle().split("@");
        String execCycleStyle = execCycleParams[0];

        boolean optResult = false;
        // daily@HHmmss-每天  自动生成5天内 执行计划
        if (execCycleStyle.equals("daily")) {
            optResult = createDailyTaskStepExecByDaily(obj);
        }

        // everyHour@HHmmss-每小时 自动生成5天内 执行计划
        if (execCycleStyle.equals("everyHour")) {
            try {
                optResult = createDailyTaskStepExecByEveryHour(obj);
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }

        }

        // specifyDay@12,12@HHmmss-指定日期  根据指定日期 生成执行计划
        if (execCycleStyle.equals("specifyDay")) {
            optResult = createDailyTaskStepExecBySpecifyDay(obj);

        }
        // specifyTime@12,23@HHmmss
        if (execCycleStyle.equals("specifyTime")) {
            optResult = createDailyTaskStepExecBySpecifyTime(obj);

        }

        return optResult;

    }

    /**
     * 创建 日间跑批任务
     *
     * @param obj      日间跑批发布记录
     * @param execDate 执行日期
     * @param execTime 执行时间
     * @return
     */
    private boolean createDailyTaskStepExec(BatchDailyBasicTaskPublish obj, String execDate, String execTime) {

        List<BatchDailyBasicTaskStepExec> list = dailyBasicTaskStepExecService.list(new LambdaQueryWrapper<BatchDailyBasicTaskStepExec>()
                .eq(BatchDailyBasicTaskStepExec::getStepNo, obj.getStepNo()).eq(BatchDailyBasicTaskStepExec::getExecDate, execDate)
                .eq(BatchDailyBasicTaskStepExec::getExecTime, execTime).eq(BatchDailyBasicTaskStepExec::getBatchSysCode, obj.getBatchSysCode())
                .eq(BatchDailyBasicTaskStepExec::getExecStatus, "0")
        );

        if (list.size() > 0) {
            return false;
        }
        BatchDailyBasicTaskStepExec dailytaskStepExec = new BatchDailyBasicTaskStepExec();
        dailytaskStepExec.setBatchSysCode(obj.getBatchSysCode());
        dailytaskStepExec.setStepParams(obj.getStepParams());
        dailytaskStepExec.setStepParamsDescription(obj.getStepParamsDescription());
        dailytaskStepExec.setStepParamsVersion(obj.getStepParamsVersion());
        dailytaskStepExec.setTaskPubId(obj.getTaskPubId());
        dailytaskStepExec.setStepNo(obj.getStepNo());
        dailytaskStepExec.setStepName(obj.getStepName());
        dailytaskStepExec.setIsReplay(obj.getIsReplay());
        dailytaskStepExec.setExecStatus("0");
        dailytaskStepExec.setSliceReqClass(obj.getSliceReqClass());
        dailytaskStepExec.setSliceServiceClass(obj.getSliceServiceClass());
        dailytaskStepExec.setTaskExecid(SernoFactory.createDailyTaskStepExecTaskPubId(obj.getTaskPubId(), execDate + execTime));
        dailytaskStepExec.setExecDate(execDate);
        dailytaskStepExec.setExecTime(execTime);
        return dailyBasicTaskStepExecService.save(dailytaskStepExec);

//        // 针对 重复信息 更新
//        for (BatchDailyBasicTaskStepExec objTemp : list) {
//            objTemp.setExecStatus("6");
//            objTemp.setRtnDesc("日间跑批计划" + obj.getTaskPubId() + "覆盖！");
//            dailyBasicTaskStepExecService.updateById(objTemp);
//        }

    }

    private boolean createDailyTaskStepExecBySpecifyTime(BatchDailyBasicTaskPublish obj) {
        log.info("createDailyTaskStepExecBySpecifyTime -> create batch_daily_task_step_exec start!");

        String[] execCycleParams = obj.getExecCycle().split("@");
        String[] execTimeList = execCycleParams[1].split(",");
        //String mwbpTransDay = parameterUtil.getParameterByCode(CommonConstant.MWBP_TRANS_DAY);
        String startExecDay = obj.getStartDate();
        boolean insertDailyTaskStepExec = true;

        for (String execTime : execTimeList) {

            if (dailyBasicTaskStepExecService.count(new LambdaQueryWrapper<BatchDailyBasicTaskStepExec>()
                    .eq(BatchDailyBasicTaskStepExec::getTaskExecid, SernoFactory.createDailyTaskStepExecTaskPubId(obj.getTaskPubId(),
                            startExecDay + execTime))) == 0) {

                insertDailyTaskStepExec = createDailyTaskStepExec(obj, startExecDay, execTime);

                if (!insertDailyTaskStepExec) {
                    log.info("createDailyTaskStepExecBySpecifyTime -> create batch_daily_task_step_exec error!");

                    break;
                }
            }



        }
        // 新增失败 删除 已生成 日间跑批任务
        if (!insertDailyTaskStepExec) {
            dailyBasicTaskPublishService.deleteByTaskPubId(obj.getBatchSysCode(), obj.getTaskPubId());
            log.info("createDailyTaskStepExecBySpecifyTime -> create batch_daily_task_step_exec rollback![" + obj.getBatchSysCode() + "][" + obj.getTaskPubId() + "]");

        }
        log.info("createDailyTaskStepExecBySpecifyTime -> create batch_daily_task_step_exec end! result is " + insertDailyTaskStepExec);

        return insertDailyTaskStepExec;


    }

    private boolean createDailyTaskStepExecBySpecifyDay(BatchDailyBasicTaskPublish obj) {
        log.info("createDailyTaskStepExecBySpecifyDay -> create batch_daily_task_step_exec start!");

        String[] execCycleParams = obj.getExecCycle().split("@");
        String[] execDateList = execCycleParams[1].split(",");
        String execTime = execCycleParams[2];
        String startDate = obj.getStartDate();
        String endDate = obj.getEndDate();

        boolean insertDailyTaskStepExec = true;
        for (String execDate : execDateList) {

            if (dailyBasicTaskStepExecService.count(new LambdaQueryWrapper<BatchDailyBasicTaskStepExec>()
                    .eq(BatchDailyBasicTaskStepExec::getTaskExecid, SernoFactory.createDailyTaskStepExecTaskPubId(obj.getTaskPubId(),
                            execDate + execTime))) == 0) {

                insertDailyTaskStepExec = createDailyTaskStepExec(obj, execDate, execTime);

                if (!insertDailyTaskStepExec) {
                    log.info("createDailyTaskStepExecBySpecifyDay -> create batch_daily_task_step_exec error!");

                    break;
                }
            }
            if (Long.compare(Long.parseLong(execDate), Long.parseLong(startDate)) < 0 || Long.compare(Long.parseLong(execDate),
                    Long.parseLong(endDate)) > 0) {
                break;
            }


        }

        // 新增失败 删除 已生成 日间跑批任务
        if (!insertDailyTaskStepExec) {
            dailyBasicTaskPublishService.deleteByTaskPubId(obj.getBatchSysCode(), obj.getTaskPubId());
            log.info("createDailyTaskStepExecBySpecifyDay -> create batch_daily_task_step_exec rollback![" + obj.getBatchSysCode() + "][" + obj.getTaskPubId() + "]");

        }

        log.info("createDailyTaskStepExecBySpecifyDay -> create batch_daily_task_step_exec end! result is " + insertDailyTaskStepExec);

        return insertDailyTaskStepExec;

    }

    /**
     * everyHour@HHmmss-每小时 自动生成5天内 执行计划
     */
    public boolean createDailyTaskStepExecByEveryHour(BatchDailyBasicTaskPublish obj) throws ParseException {
        log.info("createDailyTaskStepExecByEveryHour -> create batch_daily_task_step_exec start!");

        int dayNum = 1 * 24;
        String[] execCycleParams = obj.getExecCycle().split("@");
        String execCycleParam = execCycleParams[1];
        // 根据创建时间 和 上送日期确认 计划初始时间
        String mwbpTransDay = parameterUtil.getParameterByCode(CommonConstant.MWBP_TRANS_DAY);
        String startExecDay =
                DateUtils.str2Date(obj.getStartDate(), new SimpleDateFormat("yyyyMMdd")).getTime() > DateUtils.str2Date(mwbpTransDay,
                new SimpleDateFormat("yyyyMMdd")).getTime() ? obj.getStartDate() : mwbpTransDay;
        String startExecTime = execCycleParam;
        String endDate = obj.getEndDate();
        boolean insertDailyTaskStepExec = true;

        for (int i = 0; i < dayNum; i++) {

            Date execDate_date = new SimpleDateFormat("yyyyMMddHHmmss").parse(startExecDay + startExecTime);
            // 小时 循环
            if (dailyBasicTaskStepExecService.count(new LambdaQueryWrapper<BatchDailyBasicTaskStepExec>()
                    .eq(BatchDailyBasicTaskStepExec::getTaskExecid, SernoFactory.createDailyTaskStepExecTaskPubId(obj.getTaskPubId(),
                            startExecDay + startExecTime))) == 0) {

                insertDailyTaskStepExec = createDailyTaskStepExec(obj, startExecDay, startExecTime);

                if (!insertDailyTaskStepExec) {
                    log.info("createDailyTaskStepExecByEveryHour -> create batch_daily_task_step_exec error!");

                    break;
                }
            }

            String temp_execDate = CommonUtil.getFullDateTimeByDiffDateHour(execDate_date, 1);
            startExecDay = temp_execDate.substring(0, 8);
            startExecTime = temp_execDate.substring(8);

            if (Long.compare(Long.parseLong(startExecDay), Long.parseLong(endDate)) > 0) {
                break;
            }
        }

        // 新增失败 删除 已生成 日间跑批任务
        if (!insertDailyTaskStepExec) {
            dailyBasicTaskPublishService.deleteByTaskPubId(obj.getBatchSysCode(), obj.getTaskPubId());
            log.info("createDailyTaskStepExecByEveryHour -> create batch_daily_task_step_exec rollback![" + obj.getBatchSysCode() + "][" + obj.getTaskPubId() + "]");

        }
        log.info("createDailyTaskStepExecByEveryHour -> create batch_daily_task_step_exec end! result is " + insertDailyTaskStepExec);

        return insertDailyTaskStepExec;
    }

    /**
     * daily@HHmmss-每天  自动生成5天内 执行计划
     * 发现 重复 执行计划 返回执行失败
     */
    public boolean createDailyTaskStepExecByDaily(BatchDailyBasicTaskPublish obj) {
        log.info("createDailyTaskStepExecByDaily -> create batch_daily_task_step_exec start!");
        int dayNum = 5;
        String[] execCycleParams = obj.getExecCycle().split("@");
        String execCycleParam = execCycleParams[1];
        // 根据创建时间 和 上送日期确认 计划初始时间
        String mwbpTransDay = parameterUtil.getParameterByCode(CommonConstant.MWBP_TRANS_DAY);
        //String currentTime = CommonUtil.getFullDateTimeByDiffDateHour(new Date(), 1);
        // 增加对 日间跑批计划 startDate 和 endDate 支持
//        String startExecDay = (Long.parseLong(currentTime) < Long.parseLong(mwbpTransDay + execCycleParam)) ? mwbpTransDay :
//                CommonUtil.getDayByParameter(mwbpTransDay, 1);
        String startExecDay = DateUtils.str2Date(obj.getStartDate(), new SimpleDateFormat("yyyyMMdd")).getTime() > DateUtils.str2Date(mwbpTransDay,
                new SimpleDateFormat("yyyyMMdd")).getTime() ? obj.getStartDate() : mwbpTransDay;

        // 创建 两个日期相差几天
        dayNum = DateUtils.str2Date(CommonUtil.getDayByParameter(startExecDay, dayNum), new SimpleDateFormat("yyyyMMdd")).getTime()
                <= DateUtils.str2Date(obj.getEndDate(), new SimpleDateFormat("yyyyMMdd")).getTime()
                ? dayNum :
                ((int) ((DateUtils.str2Date(obj.getEndDate(), new SimpleDateFormat("yyyyMMdd")).getTime() - DateUtils.str2Date(startExecDay,
                        new SimpleDateFormat("yyyyMMdd")).getTime()) / (24 * 60 * 60 * 1000)) + 1);
        boolean insertDailyTaskStepExec = true;

        for (int i = 0; i < dayNum; i++) {

            if (dailyBasicTaskStepExecService.count(new LambdaQueryWrapper<BatchDailyBasicTaskStepExec>()
                    .eq(BatchDailyBasicTaskStepExec::getTaskExecid, SernoFactory.createDailyTaskStepExecTaskPubId(obj.getTaskPubId(),
                            startExecDay + execCycleParam))) == 0) {
                insertDailyTaskStepExec = createDailyTaskStepExec(obj, startExecDay, execCycleParam);

                if (!insertDailyTaskStepExec) {
                    log.info("createDailyTaskStepExecByDaily -> create batch_daily_task_step_exec error!");
                    break;
                }
            }


            startExecDay = CommonUtil.getDayByParameter(startExecDay, 1);
        }

        // 新增失败 删除 已生成 日间跑批任务
        if (!insertDailyTaskStepExec) {
            dailyBasicTaskPublishService.deleteByTaskPubId(obj.getBatchSysCode(), obj.getTaskPubId());
            log.info("createDailyTaskStepExecByDaily -> create batch_daily_task_step_exec rollback![" + obj.getBatchSysCode() + "][" + obj.getTaskPubId() + "]");

        }
        log.info("createDailyTaskStepExecByDaily -> create batch_daily_task_step_exec end! result is " + insertDailyTaskStepExec);

        return insertDailyTaskStepExec;

    }

    private Result<String> validBatchDailyTaskPublish(BatchDailyConfirmReq taskPublish, BatchDailyBasicTaskStepSet taskStepSet) {
        if (taskStepSet == null) {
            log.info("confirmDailyTask -> batch_daily_basic_task_step_set is empty![stepNo:" + taskPublish.getStepNo() + "]");
            return Result.error("日间跑批模板为空[stepNo:" + taskPublish.getStepNo() + "]");
        }

        // 验证 步骤参数版本号 是否 一致 stepParamsVersion
        if (!taskPublish.getStepParamsVersion().equals(taskStepSet.getStepParamsVersion())) {
            log.info("confirmDailyTask -> stepParamsVersion is inconsistent!" + "[taskPublish:" + taskPublish.getStepParamsVersion() +
                    "@taskStepSet:" + taskStepSet.getStepParamsVersion() + "]");
            return Result.error("日间跑批模板stepParamsVersion不一致!请重新发起" + "[taskPublish:" + taskPublish.getStepParamsVersion() +
                    "@taskStepSet:" + taskStepSet.getStepParamsVersion() + "]");
        }

        // 验证 stepParams 合法性
        JSONObject taskPublishJsonObject = JSONObject.parseObject(taskPublish.getStepParams());
        JSONObject taskStepSetJsonObject = JSONObject.parseObject(taskStepSet.getStepParams());

        if (taskPublishJsonObject == null || taskStepSetJsonObject == null) {
            log.info("confirmDailyTask -> stepParams is invalid data" + "[taskPublish:" + taskPublish.getStepParams() + "@taskStepSet:" + taskStepSet.getStepParams() + "]");
            return Result.error("日间跑批模板stepParams不一致!请重新发起" + "[taskPublish:" + taskPublish.getStepParams() +
                    "@taskStepSet:" + taskStepSet.getStepParams() + "]");
        }
        for (String key : taskPublishJsonObject.keySet()) {
            if (!taskStepSetJsonObject.containsKey(key)) {
                log.info("confirmDailyTask -> stepParams is invalid data" + "[taskPublish:" + taskPublish.getStepParams() + "@taskStepSet:"
                        + taskStepSet.getStepParams() + "]" + "key:" + key + " is not contains!");
                return Result.error("日间跑批模板stepParams不一致!请重新发起" + "[taskPublish:" + taskPublish.getStepParams() +
                        "@taskStepSet:" + taskStepSet.getStepParams() + "]");
            }
        }
        // 验证 执行时间有效性
        Date startDate = DateUtils.str2Date(taskPublish.getStartDate(), new SimpleDateFormat("yyyyMMdd"));
        Date endDate = DateUtils.str2Date(taskPublish.getEndDate(), new SimpleDateFormat("yyyyMMdd"));

        if (startDate == null || endDate == null || endDate.getTime() < startDate.getTime()) {
            log.info("confirmDailyTask -> startDate or endDate is invalid data" + "[startDate:" + taskPublish.getStartDate() + "@endDate:" + taskPublish.getEndDate() + "]");
            return Result.error("日间跑批模板startDate或endDate 非法!请重新发起" + "[startDate:" + taskPublish.getStartDate() +
                    "@endDate:" + taskPublish.getEndDate() + "]");
        }

        // 验证 当前系统业务时间 是否 在 开始和结束时间范围中 endDate >= 业务时间
        Date mwbpTransDay = DateUtils.str2Date(parameterUtil.getParameterByCode(CommonConstant.MWBP_TRANS_DAY), new SimpleDateFormat("yyyyMMdd"));

        if (endDate.getTime() < mwbpTransDay.getTime()) {
            log.info("confirmDailyTask -> endDate < mwbpTransDay" + "[endDate:" + taskPublish.getEndDate() + "@mwbpTransDay:"
                    + parameterUtil.getParameterByCode(CommonConstant.MWBP_TRANS_DAY) + "]");
            return Result.error("日间跑批模板endDate 非法 其小于当前业务周期!请重新发起" + "[endDate:" + taskPublish.getEndDate() +
                    "@mwbpTransDay:" + parameterUtil.getParameterByCode(CommonConstant.MWBP_TRANS_DAY) + "]");
        }

        return Result.ok();
    }

    /**
     * 验证对象合法性<br/>
     *
     * @param taskPublish 日间跑批任务对象
     * @return 验证逻辑：<br>
     * TaskPubId or BatchSysCode 不能为空
     */
    public Result<String> checkCancelDailyTask(BatchDailyCancelReq taskPublish) {
        if (Strings.isBlank(taskPublish.getTaskPubId()) || Strings.isBlank(taskPublish.getBatchSysCode())) {
            log.info("checkCancelDailyTask -> TaskPubId or BatchSysCode is empty!");
            return Result.error(" TaskPubId or BatchSysCode 不能为空");
        }
        BatchDailyBasicTaskPublish dailyTaskPubObj =
                dailyBasicTaskPublishService.getOne(new LambdaQueryWrapper<BatchDailyBasicTaskPublish>()
                        .eq(BatchDailyBasicTaskPublish::getTaskPubId, taskPublish.getTaskPubId()));
        if (dailyTaskPubObj == null) {
            return Result.error("跑批日间任务请求表不存在[taskPubId]为");
        }

        return Result.ok();
    }


    public Result<String> cancelDailyTask(BatchDailyCancelReq taskPublish) {
        BatchDailyBasicTaskPublish obj;
        boolean taskPublishOptResult = false;

        obj = dailyBasicTaskPublishService.getOne(new LambdaQueryWrapper<BatchDailyBasicTaskPublish>()
                .eq(BatchDailyBasicTaskPublish::getTaskPubId, taskPublish.getTaskPubId())
                .eq(BatchDailyBasicTaskPublish::getBatchSysCode, taskPublish.getBatchSysCode()));
        if (obj == null) {
            return Result.error("跑批日间任务请求表不存在[taskPubId]为" + taskPublish.getTaskPubId());
        }

        // 跑批日间任务发布状态 (0-待发布; 1-发布中; 9-任务终止; )
        if (!obj.getTaskPubStauts().equals("9")) {
            // 更新 跑批日间任务对象 发布状态
            obj.setTaskPubStauts("9");
            taskPublishOptResult = dailyBasicTaskPublishService.updateById(obj);
        } else {
            taskPublishOptResult = true;
        }

        if (!taskPublishOptResult) {
            // 操作 跑批日间任务对象 失败
            return Result.error("跑批日间任务请求表[taskPubId]为" + taskPublish.getTaskPubId() + "操作失败！");
        }

        // 清理  跑批平台-跑批日间任务执行表[batch_daily_basic_task_step_exec]
        dailyBasicTaskStepExecService.update(new BatchDailyBasicTaskStepExec().setExecStatus("6"),
                new LambdaUpdateWrapper<BatchDailyBasicTaskStepExec>()
                        .eq(BatchDailyBasicTaskStepExec::getTaskPubId, taskPublish.getTaskPubId())
                        .eq(BatchDailyBasicTaskStepExec::getBatchSysCode, taskPublish.getBatchSysCode())
                        .in(BatchDailyBasicTaskStepExec::getExecStatus, new ArrayList<>(Arrays.asList("0", "4", "5")))
        );

        return Result.ok("success");

    }
}
